package com.latinia.limsp.test;
import java.util.Properties;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import com.latinia.limsp.db.MsgPersistence;
import com.latinia.limsp.test.ltimmer.TestTimerTask;
import com.latinia.limsp.util.event.FormatterEvent;
import com.latinia.limsp.util.message.xml.MessageFormatterFactory;
/**
 * Clase hilo que lee las colas para recibir los mensajes. 
 * 
 * */
public class ListenerCollectorOut implements Runnable{
	boolean logActive;
	static int i=0;//Permite verificar el inicio del Timmer
	private QueueConnection queueConnection;
	private QueueSession queueSession;
	private MessageConsumer consumer;
	private Destination destination;
	private XMLManager manager;
	MsgPersistence persistence;
	int contador=0;
	int contadorSMS=0,contadorEmail=0,contadorPns=0;
	String status;
	TestTimerTask timerTask;
	long sleepTime=3000;
	long sleepTimeInit;
	private long timeStopReceive;
	private boolean stopReceive=false;
	public ListenerCollectorOut(XMLManager manager, String queue, TestTimerTask timerTask, boolean active){ 
		logActive=active;
		sleepTime =Long.parseLong(manager.getPropColectorOut().getProperty("sleepTime", "0"));
		sleepTimeInit=Long.parseLong(manager.getPropColectorOut().getProperty("sleepTimeInit", "0"));	
		if(manager.getPropColectorOut().getProperty("stopReceive")!=null){
			timeStopReceive=Long.parseLong(manager.getPropColectorOut().getProperty("stopReceive"));
			stopReceive=true;
		}
		this.timerTask=timerTask;
		this.manager=manager;
    	try {
    		persistence= new MsgPersistence(manager.getDbclass(), manager.getDburi(), manager.getDbuser(), manager.getDbpassword(),manager.isUseDB());
		} catch (Exception e) {
			SDPLog.outErr(e);
		}			 						
        try{
        	Properties props = new Properties();
	        props.setProperty("java.naming.factory.initial",manager.getPropColectorOut().getProperty("factoryinitial","weblogic.jndi.WLInitialContextFactory"));
	        props.setProperty("java.naming.provider.url",manager.getPropColectorOut().getProperty("providerUrl"));
	        props.setProperty(InitialContext.SECURITY_PRINCIPAL,manager.getPropColectorOut().getProperty("login"));
	        props.setProperty(InitialContext.SECURITY_CREDENTIALS,manager.getPropColectorOut().getProperty("password"));
        	InitialContext ctxt = new InitialContext(props);	
	        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ctxt.lookup(manager.getPropColectorOut().getProperty("connectionFactory","latinia/limsp/jms/connectionFactory/XAConnectionFactory"));
        	queueSession=(QueueSession)ServiceLocator.getObject("session");	        	
	        if(queueSession==null){		        				        
		        queueConnection = queueConnectionFactory.createQueueConnection();
		        queueConnection.start();
		        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
	        }
	        destination = (Destination) ctxt.lookup(queue);
	        consumer = queueSession.createConsumer(destination, "collector='TRAFFICTEST'");	
        }
        catch(Exception error){
        	SDPLog.outErr(error);	        	
        }
	}
	@Override
	public   void run() {
		System.out.println();
		
		while(true){
			try {		
				
				if(i==0){					
					Thread.sleep(sleepTimeInit);
					i=1;
				}
				else{					
					Thread.sleep(sleepTime);
				}
				TextMessage message=null;
				if(stopReceive){					
					message=(TextMessage)consumer.receive(timeStopReceive);
				}				
				else{
					message=(TextMessage)consumer.receive();
				}
				if(message==null){
					break;
				}
				TransactionXML transaction= new TransactionXML(message.getText());
				manager.setXMLtransaction(message.getText());				
				persistence.insertMsgOut(transaction.getIdMSGOut(),message.getText(),transaction.getIdTransaction());
				String refTestCase=persistence.getTestCase(transaction.getIdMSGOut());
				Contract c=manager.getContract(refTestCase);
//				System.out.println("Test Case: "+refTestCase+" para el id: "+transaction.getIdMSGOut());
				SDPLog.extInfo_out("out","colectorOut",message.getText()); 
				FormatterEvent formatter,formatterFrom;
				
				status=manager.getContractStatus()!=null?manager.getContractStatus()[0]!=null?manager.getContractStatus()[0].getState():null:null;
//				System.out.println("Estado por defecto: "+status);
				boolean statusByContract=false;
				if(transaction.getTransactionType().equals("sms")){
					if(c!=null){
						if(c.getState()!=null){
							status=c.getState();
							System.out.println("Estado por contrato: "+status);
							statusByContract=true;
						}
					}
					if(manager.getContractStatus()!=null&&manager.getContractStatus()[1]!=null&&!statusByContract){
						status=manager.getContractStatus()[1].getState();
						logOut("Estado por mensaje: "+status);
					}
					contadorSMS++;
					if(timerTask!=null){
						System.out.println("Mensaje SMS recibido...."+contadorSMS+" "+timerTask.getSmsMsgCounter());
					}
					else{
						System.out.println("Mensaje SMS recibido...."+contadorSMS);
					}
					
					if(status!=null){	
						formatter=new FormatterEvent(FormatterEvent.TYPE_SMS,transaction.getIdTransaction(),""+System.currentTimeMillis());
						formatter.setInfo(transaction.getMessageId(), transaction.getIdclause(), transaction.getIdAddressTo(), transaction.getTo(),
								transaction.getIdProduct(),transaction.getRefProduct(), MessageFormatterFactory.createUniqueID(new Object()));
						formatter.setAddressRef(transaction.getIdAddressTo(),transaction.getTo());
						SendMessage sendState= new SendMessage(manager.getPropQueueState());
						sendState.openJMSQueues();
						while (status.contains("|")) {
							String part=status.substring(0,status.indexOf("|")).trim();
							formatter.setStatus(""+System.currentTimeMillis(),part.substring(0,part.indexOf(",")),part.substring(part.indexOf(",")+1));
							sendState.sendByJMS(formatter.toString());							
							status = status.substring(status.indexOf("|") + 1);
						}
						formatter.setStatus(""+System.currentTimeMillis(),status.substring(0,status.indexOf(",")),status.substring(status.indexOf(",")+1));
						sendState.sendByJMS(formatter.toString());						
					}
				
				}
				else if(transaction.getTransactionType().equals("email")){
					if(c!=null){
						if(c.getState()!=null){
							status=c.getState();
							statusByContract=true;
						}
					}
					if(manager.getContractStatus()!=null&&manager.getContractStatus()[2]!=null&&!statusByContract){
						status=manager.getContractStatus()[2].getState();
					}
					contadorEmail++;
					if(timerTask!=null){
						System.out.println("Mensaje Email recibido...."+contadorEmail+" "+timerTask.getEmailMsgCounter());
					}
					else{
						System.out.println("Mensaje Email recibido...."+contadorEmail);
					}
					if(status!=null){	
						long ts=System.currentTimeMillis();	
						formatterFrom=new FormatterEvent(FormatterEvent.TYPE_EMAIL,transaction.getIdTransaction(),""+ts);
						formatterFrom.setInfo(transaction.getMessageId(), transaction.getIdclause(), transaction.getIdAddressFrom(), transaction.getFrom(),transaction.getIdProduct(),transaction.getRefProduct(), MessageFormatterFactory.createUniqueID(new Object()));
						formatterFrom.setAddressRef(transaction.getIdAddressFrom(),transaction.getFrom());
						formatterFrom.setStatus(""+ts, "2", "2");
						ts=System.currentTimeMillis();
						formatter=new FormatterEvent(FormatterEvent.TYPE_EMAIL,transaction.getIdTransaction(),""+ts);
						formatter.setInfo(transaction.getMessageId(), transaction.getIdclause(), transaction.getIdAddressTo(), transaction.getTo(),transaction.getIdProduct(),transaction.getRefProduct(), MessageFormatterFactory.createUniqueID(new Object()));
						formatter.setAddressRef(transaction.getIdAddressTo(),transaction.getTo());
						SendMessage sendState= new SendMessage(manager.getPropQueueState());
						sendState.openJMSQueues();
						sendState.sendByJMS(formatterFrom.toString());
						while (status.contains("|")) {
							String part=status.substring(0,status.indexOf("|")).trim();							
							formatter.setStatus(""+System.currentTimeMillis(),part.substring(0,part.indexOf(",")),part.substring(part.indexOf(",")+1));
							sendState.sendByJMS(formatter.toString());							
							status = status.substring(status.indexOf("|") + 1);
						}												
						formatter.setStatus(""+System.currentTimeMillis(),status.substring(0,status.indexOf(",")),status.substring(status.indexOf(",")+1));
						sendState.sendByJMS(formatter.toString());
					}					
				}
				else if(transaction.getTransactionType().equals("pns")){//por confirmar
					if(c!=null){
						if(c.getState()!=null){
							status=c.getState();
							statusByContract=true;
						}
					}
					if(manager.getContractStatus()!=null&&manager.getContractStatus()[3]!=null&&!statusByContract){
						status=manager.getContractStatus()[3].getState();
					}
					contadorPns++;
					if(timerTask!=null){
						System.out.println("Mensaje PNS recibido..."+contadorPns+" "+timerTask.getPnsMsgCounter());
					}
					else{
						System.out.println("Mensaje PNS recibido..."+contadorPns);
					}
					if(status!=null){
						formatter=new FormatterEvent(FormatterEvent.TYPE_PNS,transaction.getIdTransaction(),""+System.currentTimeMillis());
						formatter.setInfo(transaction.getMessageId(), transaction.getIdclause(), transaction.getIdAddressTo(), transaction.getTo(),transaction.getIdProduct(),transaction.getRefProduct(), MessageFormatterFactory.createUniqueID(new Object()));
						formatter.setAddressRef(transaction.getIdAddressTo(),transaction.getTo());											
						// Abriendo las colas.
						SendMessage sendState= new SendMessage(manager.getPropQueueState());
						sendState.openJMSQueues();
						while (status.contains("|")) {
							String part=status.substring(0,status.indexOf("|")).trim();							
							formatter.setStatus(""+System.currentTimeMillis(),part.substring(0,part.indexOf(",")),part.substring(part.indexOf(",")+1));
							sendState.sendByJMS(formatter.toString());							
							status = status.substring(status.indexOf("|") + 1);
						}	
						formatter.setStatus(""+System.currentTimeMillis(),status.substring(0,status.indexOf(",")),status.substring(status.indexOf(",")+1));
						sendState.sendByJMS(formatter.toString());																		
					}
				}				
			} catch (InterruptedException e) {
				SDPLog.outErr(e);				
				break;
			}
			catch (Exception e){
				SDPLog.outErr(e);				
				break;
			}
		}		
	}
	private void logOut(String log) {
		if (logActive) {
			System.out.println(log);
		}
	}
}
